package com.cafe.pro.util;

import com.cafe.pro.dto.KeyPairConfig;

import java.security.*;
import java.security.spec.X509EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class KeyUtil {

    public static KeyPair parseKeyPair(KeyPairConfig keyPairConfig) throws Exception {
        byte[] pubBytes = Base64.getDecoder().decode(keyPairConfig.getPublicKey());
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubBytes);
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(pubSpec);

        byte[] privBytes = Base64.getDecoder().decode(keyPairConfig.getPrivateKey());
        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privBytes);
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(privSpec);

        return new KeyPair(publicKey, privateKey);
    }


    /**
     * 生成 RSA 公私钥对，并封装为 KeyPairConfig 对象
     */
    public static KeyPairConfig generateKeyPairConfig() throws Exception {
        // 1. 生成 RSA 密钥对
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048); // 可根据需要调整密钥长度
        KeyPair keyPair = kpg.generateKeyPair();

        // 2. 编码为 Base64 字符串
        String publicKeyStr = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
        String privateKeyStr = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());

        // 3. 封装到 KeyPairConfig
        return new KeyPairConfig(publicKeyStr, privateKeyStr);
    }

    public static void main(String[] args) throws Exception {
        KeyPairConfig config = KeyUtil.generateKeyPairConfig();
        System.out.println("Public Key: " + config.getPublicKey());
        System.out.println("Private Key: " + config.getPrivateKey());
    }
}
